package org.aynu.userservice.controller;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import org.aynu.userservice.common.UserResponse;
import org.aynu.userservice.mapper.WorkMapper;
import org.aynu.userservice.model.User;
import org.aynu.userservice.model.Visitor;
import org.aynu.userservice.model.Work;
import org.aynu.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author 小粥
 * @since 2025/03/02
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Validated
public class UserController {

    /** 用户服务 */
    private final UserService userService;

    /*工人mapper*/
    private final WorkMapper workMapper;

    /**
     * 用户控制器构造方法
     *
     * @param userService 用户服务
     * @author 小粥
     * @since 2025/03/03
     */
    @Autowired
    public UserController(UserService userService, WorkMapper workMapper) {
        this.userService = userService;
        this.workMapper = workMapper;
    }

    // ----------------------- 用户相关方法 -----------------------

    /**
     * 注册用户
     *
     * @param userEntity 用户实体
     * @return 用户注册响应
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<String>> register(@Valid @RequestBody User userEntity) {
        log.info("收到用户注册请求，用户名：{}", userEntity.getUsername());
        UserResponse<String> response = userService.register(userEntity);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 用户登录
     *
     * @param userEntity 用户实体
     * @return 用户登录响应
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Map<String, Object>>> login(@Valid @RequestBody User userEntity) {
        log.info("收到用户登录请求，用户名：{}", userEntity.getUsername());
        UserResponse<Map<String, Object>> response = userService.login(userEntity);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    @RequestMapping(value = "/selectUser",method = RequestMethod.POST)
    public ResponseEntity<UserResponse<User>> selectResident(@RequestBody Map<String, Object> map) {
        Integer userId = Integer.valueOf(map.get("userId").toString());
        log.info("收到用户查询请求，用户Id：{}", userId);
        UserResponse<User> response = userService.selectResident(userId);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /*查询所有用户的userId*/
    @RequestMapping(value = "/selectAllUserId", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Map<String, Object>>> selectAllUserId() {
        log.info("收到用户查询请求，用户Id：{}");
        UserResponse<Map<String, Object>> response = userService.selectAllUserId();
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 更新用户信息
     *
     * @param userEntity 用户实体
     * @return 更新结果响应
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Integer>> updateUser(@Valid @RequestBody User userEntity) {
        log.info("收到用户更新请求，用户ID：{}", userEntity.getUserId());
        UserResponse<Integer> response = userService.updateUser(userEntity);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 重置用户密码
     *
     * @param map 请求参数（包含用户名、邮箱和新密码）
     * @return 重置密码结果响应
     */
    @RequestMapping(value = "/forget", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<String>> resetPassword(@RequestBody Map<String, Object> map) {
        log.info("收到密码重置请求，用户参数：{}", map);
        try {
            String username = (String) map.get("username");
            String email = (String) map.get("email");
            String newPassword = (String) map.get("newPasswordHash");
            if (username == null || email == null || newPassword == null) {
                return ResponseEntity.badRequest()
                        .body(UserResponse.error("用户名、邮箱和新密码均不能为空"));
            }
            UserResponse<String> response = userService.resetPassword(username, email, newPassword);
            return ResponseEntity.status(HttpStatus.OK).body(response);
        } catch (Exception e) {
            log.error("处理密码重置请求时发生异常：{}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(UserResponse.error("服务器异常：" + e.getMessage()));
        }
    }

    /**
     * 获取所有用户
     *
     * @param params 分页参数（页码和每页大小）
     * @return 用户列表响应
     */
    @RequestMapping(value = "/all", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Map<String, Object>>> getAllUsers(
             Map<String, Integer> params) {
        int pageNum = params.getOrDefault("pageNum", 1);
        int pageSize = params.getOrDefault("pageSize", 10);
        log.info("收到获取所有用户请求，页码：{}，每页大小：{}", pageNum, pageSize);
        UserResponse<Map<String, Object>> response = userService.getAllUsers(pageNum, pageSize);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /*获取用户所有信息*/
    @RequestMapping(value = "/selectAllUser", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<List<User>>> selectAllUser() {
        log.info("收到获取所有用户请求");
        UserResponse<List<User>> response = userService.selectAllUser();
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /*获取用户总数量*/
    @RequestMapping(value = "/count", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Integer>> getUserCount() {
        log.info("收到获取用户总数量请求");
        UserResponse<Integer> response = userService.getUserCount();
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    // ----------------------- 管理员相关方法 -----------------------

    /**
     * 管理员创建用户
     *
     * @param userEntity 用户实体
     * @return 创建结果响应
     */
    @RequestMapping(value = "/admin/create", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Integer>> createUserByAdmin(@Valid @RequestBody User userEntity) {
        log.info("收到管理员创建用户请求，用户名：{}", userEntity.getUsername());
        UserResponse<Integer> response = userService.createUser(userEntity);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 管理员更新用户
     *
     * @param userEntity 用户实体
     * @return 更新结果响应
     */
    @RequestMapping(value = "/admin/update", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Boolean>> updateUserByAdmin(@Valid @RequestBody User userEntity) {
        log.info("收到管理员更新用户请求，用户ID：{}", userEntity.getUserId());
        UserResponse<Boolean> response = userService.updateUserByAdmin(userEntity);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * @param map
     * @return {@link ResponseEntity }<{@link UserResponse }<{@link Boolean }>>
     * @author 小粥
     * @since 2025/03/05
     */

    @RequestMapping(value = "/admin/delete", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Boolean>> deleteUserByAdmin(@RequestBody  Map<String, Object> map) {
        int userId = Integer.parseInt(map.get("userId").toString());
        log.info("收到管理员删除用户请求，用户ID：{}", userId);
        UserResponse<Boolean> response = userService.deleteUser(userId);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 创建管理员
     *
     * @param adminEntity 管理员实体
     * @return 创建结果响应
     */
    @RequestMapping(value = "/admin/create-admin", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Integer>> createAdmin(@Valid @RequestBody User adminEntity) {
        log.info("收到创建管理员请求，管理员用户名：{}", adminEntity.getUsername());
        UserResponse<Integer> response = userService.createAdmin(adminEntity);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }


    /*获取前五条用户数据*/
    @RequestMapping(value = "/get-five-users", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Map<String, Object>>> getFiveUsers() {
        log.info("收到获取前五条用户数据的请求");
        UserResponse<Map<String, Object>> response = userService.getFiveUsers();
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }


    // ----------------------- 访客相关方法 -----------------------

    /**
     * 登记访客
     *
     * @param map 请求参数（包含访客信息和居民信息）
     * @return 登记结果响应
     */
    @RequestMapping(value = "/visitor/register", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Integer>> registerVisitor(@RequestBody Map<String, Object> map) {
        try {
            Map<String, Object> visitorMap = (Map<String, Object>) map.get("visitor");
            if (visitorMap == null) {
                return ResponseEntity.badRequest().body(UserResponse.error("访客信息不能为空"));
            }
            Visitor visitor = new Visitor();
            visitor.setName((String) visitorMap.get("name"));
            visitor.setPhoneNumber((String) visitorMap.get("phoneNumber"));
            visitor.setPurpose((String) visitorMap.get("purpose"));

            // 解析 arrivalTime
            String arrivalTimeStr = (String) visitorMap.get("arrivalTime");
            if (arrivalTimeStr != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date arrivalTime = sdf.parse(arrivalTimeStr);
                    visitor.setArrivalTime(arrivalTime);
                } catch (ParseException e) {
                    return ResponseEntity.badRequest().body(UserResponse.error("访问时间格式不正确，应为 yyyy-MM-dd HH:mm:ss"));
                }
            }

            // 解析 departureTime
            String departureTimeStr = (String) visitorMap.get("departureTime");
            if (departureTimeStr != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date departureTime = sdf.parse(departureTimeStr);
                    visitor.setDepartureTime(departureTime);
                } catch (ParseException e) {
                    return ResponseEntity.badRequest().body(UserResponse.error("预计离开时间格式不正确，应为 yyyy-MM-dd HH:mm:ss"));
                }
            }

            String residentNameOrPhone = (String) map.get("residentNameOrPhone");
            if (residentNameOrPhone == null) {
                return ResponseEntity.badRequest().body(UserResponse.error("居民信息不能为空"));
            }
            log.info("收到访客登记请求，访客姓名：{}，居民信息：{}", visitor.getName(), residentNameOrPhone);
            UserResponse<Integer> response = userService.registerVisitor(visitor, residentNameOrPhone);
            return ResponseEntity.status(HttpStatus.OK).body(response);
        } catch (Exception e) {
            log.error("访客登记失败：{}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(UserResponse.error("服务器异常：" + e.getMessage()));
        }
    }

    /*根据访客手机号查询访客信息*/
    @RequestMapping(value = "/visitor/query-by-phone", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<List<Visitor>>> queryVisitorByPhone(@RequestBody Map<String, Object> map) {
        String phoneNumber = (String) map.get("phoneNumber");
        log.info("收到查询访客信息请求，访客手机号：{}", phoneNumber);
        UserResponse<List<Visitor>> response = userService.queryVisitorByPhone(phoneNumber);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 审批访客
     *
     * @param params 请求参数（包含访客ID和状态）
     * @return 审批结果响应
     */
    @RequestMapping(value = "/visitor/approve", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<String>> approveVisitor(@RequestBody Map<String, Object> params) {
        try {
            Integer visitorId = (Integer) params.get("visitorId");
            String status = (String) params.get("status");
            if (visitorId == null || visitorId < 1) {
                return ResponseEntity.badRequest().body(UserResponse.error("访客ID必须大于0"));
            }
            if (status == null) {
                return ResponseEntity.badRequest().body(UserResponse.error("状态不能为空"));
            }
            log.info("收到访客审批请求，访客ID：{}，状态：{}", visitorId, status);
            UserResponse<String> response = userService.approveVisitor(visitorId, status);
            return ResponseEntity.status(HttpStatus.OK).body(response);
        } catch (Exception e) {
            log.error("审批访客失败：{}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(UserResponse.error("服务器异常：" + e.getMessage()));
        }
    }

    /**
     * 获取所有访客
     *
     * @param params 分页参数（页码和每页大小）
     * @return 访客列表响应
     */
    @RequestMapping(value = "/visitor/all", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Map<String, Object>>> getAllVisitors(Map<String, Integer> params) {
        int pageNum = params.getOrDefault("pageNum", 1);
        int pageSize = params.getOrDefault("pageSize", 10);
        log.info("收到获取所有访客请求，页码：{}，每页大小：{}", pageNum, pageSize);
        UserResponse<Map<String, Object>> response = userService.getAllVisitors(pageNum, pageSize);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 根据用户ID获取访客
     *
     * @param params 请求参数（包含用户ID、分页信息）
     * @return 访客列表响应
     */
    @RequestMapping(value = "/visitor/by-user", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<Map<String, Object>>> getVisitorsByUserId(
            @RequestBody Map<String, Integer> params) {
        Integer userId = params.get("userId");
        int pageNum = params.getOrDefault("pageNum", 1);
        int pageSize = params.getOrDefault("pageSize", 10);
        if (userId == null || userId < 1) {
            return ResponseEntity.badRequest().body(UserResponse.error("用户ID必须大于0"));
        }
        log.info("收到获取用户访客请求，用户ID：{}，页码：{}，每页大小：{}", userId, pageNum, pageSize);
        UserResponse<Map<String, Object>> response = userService.getVisitorsByUserId(userId, pageNum, pageSize);
        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 删除访客
     *
     * @param params 请求参数（包含访客ID）
     * @return 删除结果响应
     */
    @RequestMapping(value = "/visitor/delete", method = RequestMethod.POST)
    public ResponseEntity<UserResponse<String>> deleteVisitor(@RequestBody Map<String, Object> params) {
        try {
            Integer visitorId = (Integer) params.get("visitorId");
            if (visitorId == null || visitorId < 1) {
                return ResponseEntity.badRequest().body(UserResponse.error("访客ID必须大于0"));
            }
            log.info("收到删除访客请求，访客ID：{}", visitorId);
            UserResponse<String> response = userService.deleteVisitor(visitorId);
            return ResponseEntity.status(HttpStatus.OK).body(response);
        } catch (Exception e) {
            log.error("删除访客失败：{}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(UserResponse.error("服务器异常：" + e.getMessage()));
        }
    }

    // ----------------------- 异常处理 -----------------------

    /**
     * 处理非法参数异常
     *
     * @param ex 异常对象
     * @return 错误响应
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<UserResponse<String>> handleIllegalArgumentException(IllegalArgumentException ex) {
        log.warn("非法参数异常：{}", ex.getMessage());
        return ResponseEntity.badRequest().body(UserResponse.error(ex.getMessage()));
    }

    /**
     * 处理运行时异常
     *
     * @param ex 异常对象
     * @return 错误响应
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<UserResponse<String>> handleRuntimeException(RuntimeException ex) {
        log.error("运行时异常：{}", ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(UserResponse.error("服务器异常：" + ex.getMessage()));
    }

    /*查询所有工人信息*/
    @RequestMapping(value = "/selectAllWork", method = RequestMethod.POST)
    public UserResponse<List<Work>> selectAllWork() {
        List<Work> workList = workMapper.selectList(null);
        return UserResponse.success("查询所有工人信息成功",workList);
    }
}